import threading
import time


# 两个函数中都会调用相同的资源，互相等待对方结束的情况。
# 如果两个线程分别占有一部分资源并且同时等待对方的资源，就会造成死锁。

class MyThread(threading.Thread):
    def do1(self):
        global resA, resB
        if mutexA.acquire():
            msg = self.name + ' got resA'
            print(msg)  # thread2  进入了a资源,想访问b资源
            if mutexB.acquire():
                msg = self.name + ' got resB'
                print(msg)
                mutexB.release()
            mutexA.release()

    def do2(self):
        global resA, resB
        if mutexB.acquire():
            msg = self.name + ' got resB'
            print(msg)  # thread1  占用着b,想访问a
            if mutexA.acquire():
                msg = self.name + ' got resA'
                print(msg)
                mutexA.release()
            mutexB.release()

    def run(self):
        self.do1()
        self.do2()


resA = 0
resB = 0
mutexA = threading.Lock()
mutexB = threading.Lock()


def test():
    for i in range(5):
        t = MyThread()
        t.start()


if __name__ == '__main__':
    test()
